import { ElNotification } from "element-plus"
import { uploadUrl, uploadNmae } from "/config"
import { postAxios } from "/axios"
import { useIndexedDBStore } from "/store/indexedDB"
export const imageExts = ["jpg", "jpeg", "png", "gif", "bmp", "webp"]
export const videoExts = ["mp4", "webm", "ogg"]
export function isImage(fileName) {
	return imageExts.includes(fileName.split(".").pop()?.toLowerCase() ?? "")
}
export function isVideo(fileName) {
	return videoExts.includes(fileName.split(".").pop()?.toLowerCase() ?? "")
}
export function downloadFileStream(data, type, filename) {
	if (!/^application/.test(type)) {
		type = "application/" + type
	}
	const blob = new Blob([data], { type })
	const url = window.URL.createObjectURL(blob)
	const link = document.createElement("a")
	link.style.display = "none"
	link.href = url
	link.setAttribute("download", filename)
	document.body.appendChild(link)
	link.click()
	document.body.removeChild(link)
	window.URL.revokeObjectURL(url)
}
export function selectFile(indexedDBStore, { name, size, lastModified }) {
	return new Promise((resolve, reject) => {
		indexedDBStore
			.select("upload-file", "name", result => {
				if (name === result.name && size === result.size && lastModified === result.lastModified) {
					resolve({
						url: result.url,
						path: result.path,
						name: result.name,
						md5: result.md5,
					})
				}
			})
			.then(reject)
	})
}
export async function uploadFile(file) {
	if (!file) {
		return Promise.reject("文件不存在")
	}
	const name = file.name
	const size = file.size
	const lastModified = file.lastModified
	const indexedDBStore = useIndexedDBStore()
	try {
		const result = await selectFile(indexedDBStore, { name, size, lastModified })
		return result
	} catch (error) {
		const formData = new FormData()
		formData.append(uploadNmae, file)
		try {
			const { url, path, md5, name } = await postAxios(uploadUrl, formData)
			indexedDBStore.set("upload-file", {
				name: name,
				url: url,
				path: path,
				size,
				lastModified,
				md5,
			})
			return { url, path, name, md5 }
		} catch (error) {
			console.log(error)
			ElNotification({ message: "上传失败", type: "error" })
			return Promise.reject(error)
		}
	}
}
export function image2Blob(image) {
	var canvas = document.createElement("canvas")
	canvas.width = image.width
	canvas.height = image.height
	var ctx = canvas.getContext("2d")
	ctx.drawImage(image, 0, 0, image.width, image.height)
	const dataUrl = canvas.toDataURL("image/png")
	const arr = dataUrl.split(",")
	const mime = arr[0].match(/:(.*?);/)[1]
	const bstr = atob(arr[1])
	let n = bstr.length
	const u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new Blob([u8arr], { type: mime })
}
